package com.kvest.maptest.ui.activity;

import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
import com.kvest.maptest.R;
import com.kvest.maptest.datamodel.FsqVenue;
import com.kvest.maptest.ui.utils.TextIconGenerator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created with IntelliJ IDEA.
 * User: roman
 * Date: 9/3/13
 * Time: 4:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class SimpleMapActivity extends FragmentActivity {
    private static final int SEARCH_RADIUS = 150;
    private static final String API_URL = "https://api.foursquare.com/v2";
    private static final String ACCESS_TOKEN = "HJHYZAMHYKY1TTF1V3K051IO1RDSOIVF0PCE10QODYAJLC1C";

//    "id":"4d4b7104d754a06370d81259","name":"Arts & Entertainment"
//            "id":"4d4b7105d754a06372d81259","name":"College & University"
//            "id":"4d4b7105d754a06374d81259","name":"Food"
//            "id":"4d4b7105d754a06376d81259","name":"Nightlife Spot"
//            "id":"4d4b7105d754a06377d81259","name":"Outdoors & Recreation"
//            "id":"4d4b7105d754a06375d81259","name":"Professional & Other Places"
//            "id":"4e67e38e036454776db1fb3a","name":"Residence"
//            "id":"4d4b7105d754a06378d81259","name":"Shop & Service"
//            "id":"4d4b7105d754a06379d81259","name":"Travel & Transport"

    private GoogleMap map;
    private TextIconGenerator textIconGenerator;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_map);

        textIconGenerator = new TextIconGenerator(this);

        //go to frunkfurt airport
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(50.04875041258225,8.573078624904156), 18.15f), new GoogleMap.CancelableCallback() {

            @Override
            public void onFinish() {
                refresh();
            }

            @Override
            public void onCancel() {}
        });
        map.setIndoorEnabled(true);
        map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                Log.d("KVEST_TAG", cameraPosition.toString());
            }
        });

        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
            }
        });
    }

    private void refresh() {
        map.clear();
        CircleOptions circleOptions = new CircleOptions().center(map.getCameraPosition().target).radius(SEARCH_RADIUS).strokeColor(Color.GREEN).strokeWidth(4.0f);
        map.addCircle(circleOptions);

        SearchVenues searchVenues = new SearchVenues();
        searchVenues.execute(map.getCameraPosition().target);
    }

    private static String timeMilisToString(long milis) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(milis);

        return sd.format(calendar.getTime());
    }

    private static String streamToString(InputStream is) throws IOException {
        String str = "";

        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }

                reader.close();
            } finally {
                is.close();
            }

            str = sb.toString();
        }

        return str;
    }

    public static ArrayList<FsqVenue> getNearby(double latitude, double longitude) throws Exception {
        ArrayList<FsqVenue> venueList = new ArrayList<FsqVenue>();

        try {
            String v	= timeMilisToString(System.currentTimeMillis());
            String ll = String.valueOf(latitude) + "," + String.valueOf(longitude);
            URL url = new URL(API_URL + "/venues/search?ll=" + ll + "&radius=" + Integer.toString(SEARCH_RADIUS) + "&limit=50&oauth_token=" + ACCESS_TOKEN + "&v=" + v + "&categoryId=4bf58dd8d48988d1ed931735");

            //Log.d("KVEST_TAG", "Opening URL " + url.toString());

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);
            //urlConnection.setDoOutput(true);

            urlConnection.connect();

            String response	= streamToString(urlConnection.getInputStream());
            //Log.d("KVEST_TAG", "response=" + response);
            JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();

            JSONArray groups	= (JSONArray) jsonObj.getJSONObject("response").getJSONArray("venues");

            int length	= groups.length();

            for (int i = 0; i < length; i++) {
                JSONObject item = (JSONObject) groups.get(i);

                FsqVenue venue = new FsqVenue();

                venue.id = item.getString("id");
                venue.name	= item.getString("name");

                JSONObject location = (JSONObject) item.getJSONObject("location");

                venue.location	= new LatLng(Double.valueOf(location.getString("lat")), Double.valueOf(location.getString("lng")));
                //venue.address	= location.getString("address");
                venue.distance	= location.getInt("distance");
                venue.here_now	= item.getJSONObject("hereNow").getInt("count");

                venue.categories = "";
                JSONArray categories = item.getJSONArray("categories");
                for (int j = 0; j < categories.length(); ++j) {
                    venue.categories += (j != 0 ? ", " : "") + ((JSONObject)categories.get(j)).getString("name");
                }

                 venueList.add(venue);
            }
        } catch (Exception ex) {
            throw ex;
        }

        return venueList;
    }

    private class SearchVenues extends AsyncTask<LatLng, Void, ArrayList<FsqVenue>> {
        protected ArrayList<FsqVenue> doInBackground(LatLng... positions) {
            ArrayList<FsqVenue> result = null;
            try {
                result = getNearby(positions[0].latitude, positions[0].longitude);
            } catch (Exception ioException) {}
            return result;
        }


        protected void onPostExecute(ArrayList<FsqVenue> result) {
            if (result != null) {
                Log.d("KVEST_TAG", "size=" + result.size());
                for (FsqVenue fsqVenue : result) {

                    map.addMarker(new MarkerOptions()
                            .position(fsqVenue.location)
                            .title(fsqVenue.name)
                            .snippet(fsqVenue.getDescription())
                            .icon(BitmapDescriptorFactory.fromBitmap(textIconGenerator.makeIcon(fsqVenue.name))));
                }
            } else {
                Toast.makeText(SimpleMapActivity.this, "Error searching venues", Toast.LENGTH_LONG).show();
            }
        }

    }
}

